import http from 'http';
import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import initializeDb from './db';
import middleware from './middleware';
import api from './api';
import config from './config.json';
import domain from "domain";
import * as path from "path"

let app = express();
app.server = http.createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
// logger
app.use(morgan('dev'));

// 3rd party middleware
app.use(cors({
	exposedHeaders: config.corsHeaders
}));

app.use(bodyParser.json({
	limit : config.bodyLimit
}));

app.use(function (req, res, next) {
	var reqDomain = domain.create();
	reqDomain.on('error', function (err) {  // 下面抛出的异常在这里被捕获,触发此事件
		console.log('捕获到错误');
		res.send(500, err.stack);           // 成功给用户返回了 500
	});
	reqDomain.run(next);
});

// connect to db
initializeDb( db => {

	// internal middleware
	app.use(middleware({ config, db }));

	// api router
	app.use('/api', api({ config, db }));

	app.server.listen(process.env.PORT || config.port, () => {
		console.log(`Started on port ${app.server.address().port}`);
	});
});

export default app;
